package db_main

import (
	"errors"
	"fmt"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
	"strings"
	"time"

	"gorm.io/gorm"
	"longmen/server/pkg/common/api_models"
)

func GetAnchorWithdrawalsCount(param map[string]interface{}) (int64, error) {
	fName := "GetAnchorWithdrawalsCount"
	var o int64
	table := mysql.GetRTable(&models_main.AnchorWithdrawals{})
	mysql.Condition(table, param, "", "", 0, 0)
	err := table.Count(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func GetAnchorWithdrawals(param map[string]interface{}, order string, page, size int) ([]*models_main.AnchorWithdrawals, error) {
	fName := "GetAnchorWithdrawals"
	o := make([]*models_main.AnchorWithdrawals, 0)
	table := mysql.GetRTable(&models_main.AnchorWithdrawals{})
	mysql.Condition(table, param, "", order, page, size)
	err := table.Find(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

/**
 * Author: Amer
 * Function: Banks
 * Description: 获取银行列表
 */
func Banks() ([]*models_main.Banks, error) {
	fName := "Banks"
	o := make([]*models_main.Banks, 0)
	if err := mysql.GetRTable(&models_main.Banks{}).Where("status = 1").Find(&o).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		return o, nil
	} else if err != nil {
		// 包含层级错误
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
		return o, err
	}
	return o, nil
}

/**
 * Author: Amer
 * Function: Repository AddWithdraw
 * Description: 获取银行列表
 */
func AddWithdraw(req *api_models.UserWithdrawReq, user *models_main.User, session *gorm.DB) error {
	fName := "Repository AddWithdraw"
	if session == nil {
		session = global.GetX().Begin()
	}
	//判断是否支持银行
	//var bank = &models.Banks{}
	//if err := getRTable(bank).Where("status = 1 AND id = ?", param["bank_id"]).Find(bank).Error; err != nil {
	//	return fmt.Errorf("%s%s", Convert(fName), err.Error())
	//}
	//if bank.Id == 0 {
	//	return errors.New("提现银行有误，或不支持此银行")
	//}

	//判断用户是否有这个银行卡
	var userBank = &models_main.UserBank{}
	if err := mysql.GetRTable(userBank).Where("uid = ? AND id = ? And deleted = ?", user.Id, req.BankId, 0).Find(userBank).Error; err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	if userBank.Id == 0 {
		session.Rollback()
		return errors.New("银行卡号不属于该用户")
	}

	var config = &models_main.ConfigPub{}
	if err := mysql.GetRTable(config).
		Order("id asc").
		Limit(1).
		Find(config).Error; err != nil {
		session.Rollback()
		return fmt.Errorf("%s %s", util.Convert(fName), err.Error())
	}

	//判断提现金额区间
	applyAmount := req.ApplyAmount
	if config.WithdrawLimit != "" && strings.Contains(config.WithdrawLimit, "-") {
		limits := strings.Split(config.WithdrawLimit, "-")
		if applyAmount < util.S2I(limits[0]) || applyAmount > util.S2I(limits[1]) {
			session.Rollback()
			return errors.New("您单笔提现金额区间:" + config.WithdrawLimit)
		}
	}

	//提现入库
	nodes, err := util.NewNode(1)
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%d : %s", user.Id, err.Error())
	}
	if err := session.Create(&models_main.UserWithdraw{
		Uid:             user.Id,
		SerialNumber:    "T" + nodes.Generate().String(),
		ApplyAmount:     applyAmount,
		BankName:        userBank.Bank,
		BankcardName:    userBank.Name,
		BankcardAccount: userBank.Card,
		CreatedTime:     time.Now(),
	}).Error; err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	//更新克拉，失败转账补回去
	user.ProfitDiamond = user.ProfitDiamond - applyAmount
	if err := session.Model(&models_main.User{}).Where("id = ?", user.Id).Update("profit_diamond", user.ProfitDiamond).Error; err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	session.Commit()
	return nil
}

/**
 * Author: Amer
 * Function: Repository Withdraws
 * Description: 提現記錄
 */
func Withdraws(param map[string]interface{}, order string, page, size int) ([]*models_main.UserWithdraw, error) {
	fName := "Repository Withdraws"
	var data []*models_main.UserWithdraw
	table := mysql.GetRTable(&models_main.UserWithdraw{})
	mysql.Condition(table, param, "", order, page, size)
	err := table.Find(&data).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return data, err
}
